#!/usr/bin/env python
import sys
import os.path as osp
from winpython import wppm, utils
from argparse import ArgumentParser

parser = ArgumentParser(description="WinPython Package Manager: install, "\
                        "uninstall or upgrade Python packages on a Windows "\
                        "Python distribution like WinPython.")
parser.add_argument('fname', metavar='package', type=unicode,
                    help='path to a Python package')
parser.add_argument('-t', '--target', dest='target', default=sys.prefix,
                    help='path to target Python distribution '\
                         '(default: "%s")' % sys.prefix)
parser.add_argument('-i', '--install', dest='install', action='store_const',
                    const=True, default=False,
                    help='install package (this is the default action)')
parser.add_argument('-u', '--uninstall', dest='uninstall',
                    action='store_const', const=True, default=False,
                    help='uninstall package')
args = parser.parse_args()

if args.install and args.uninstall:
    raise RuntimeError, "Incompatible arguments: --install and --uninstall"

if not args.install and not args.uninstall:
    args.install = True

if not osp.isfile(args.fname):
    raise IOError, "File not found: %s" % args.fname

if utils.is_python_distribution(args.target):
    dist = wppm.Distribution(args.target)
    try:
        package = wppm.Package(args.fname)
        if package.is_compatible_with(dist):
            if args.install:
                dist.install(package)
            else:
                dist.uninstall(package)
        else:
            raise RuntimeError, "Package is not compatible with Python "\
                                "%s %dbit" % (dist.version, dist.architecture)
    except NotImplementedError:
        raise RuntimeError, "Package is not (yet) supported by WPPM"
else:
    raise WindowsError, "Invalid Python distribution %s" % args.target
